import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/utils/index.dart';

/// 登录页面视图
/// 
/// 水墨风格的登录界面，采用黑白灰色调和传统中国元素
/// 包含用户名密码表单、记住密码功能和动画效果
class LoginPage extends GetView<LoginController> {
  const LoginPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    return Stack(
      children: [
        // 背景层
        _buildBackground(),
        // 主要内容区域
        _buildMainContent(),
        // 装饰元素层
        _buildDecorations(),
      ],
    );
  }

  /// 构建水墨风格背景
  Widget _buildBackground() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF1a1a1a),    // 深灰黑
            Color(0xFF2d2d2d),    // 中灰
            Color(0xFF1a1a1a),    // 深灰黑
          ],
          stops: [0.0, 0.5, 1.0],
        ),
      ),
      child: CustomPaint(
        painter: InkWashPainter(),
        size: Size.infinite,
      ),
    );
  }

  /// 构建主要内容区域
  Widget _buildMainContent() {
    return Center(
      child: SingleChildScrollView(
        // 添加顶部padding避免与AppBar重叠，同时保持背景完整性
        padding: const EdgeInsets.only(
          left: 32.0,
          right: 32.0,
          top: 80.0,  // 减少顶部padding，因为没有标题了
          bottom: 40.0,
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Logo和标题区域
            _buildLogoSection(),
            const SizedBox(height: 40),
            // 登录表单
            _buildLoginForm(),
            const SizedBox(height: 20),
            // 忘记密码链接
            _buildForgotPasswordLink(),
            const SizedBox(height: 40),
            // 底部信息
            _buildBottomInfo(),
          ],
        ),
      ),
    );
  }

  /// 构建Logo和标题区域
  Widget _buildLogoSection() {
    return Transform.scale(
      scale: controller.logoScale.value.clamp(0.1, 2.0),
      child: Column(
        children: [
          // Logo图标
          // _buildLogo(),
          const SizedBox(height: 24),
          // 欢迎文字
          _buildWelcomeText(),
          const SizedBox(height: 8),
          // 副标题
          _buildSubtitle(),
        ],
      ),
    );
  }

  /// 构建Logo图标
  Widget _buildLogo() {
    return Container(
      width: 120,
      height: 120,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: RadialGradient(
          colors: [
            Colors.white.withOpacity(0.9),
            Colors.grey.withOpacity(0.7),
            Colors.black.withOpacity(0.8),
          ],
          stops: const [0.0, 0.7, 1.0],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 20,
            spreadRadius: 2,
          ),
        ],
      ),
      child: const Icon(
        Icons.flutter_dash,
        size: 60,
        color: Colors.black87,
      ),
    );
  }

  /// 构建欢迎文字
  Widget _buildWelcomeText() {
    return Text(
      controller.welcomeText,
      style: const TextStyle(
        fontSize: 32,
        fontWeight: FontWeight.w300,
        color: Colors.white,
        letterSpacing: 2.0,
        shadows: [
          Shadow(
            offset: Offset(1, 1),
            blurRadius: 3,
            color: Colors.black54,
          ),
        ],
      ),
    );
  }

  /// 构建副标题
  Widget _buildSubtitle() {
    return Text(
      controller.subtitleText,
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w300,
        color: Colors.white.withOpacity(0.8),
        letterSpacing: 1.0,
      ),
    );
  }

  /// 构建登录表单
  Widget _buildLoginForm() {
    return Opacity(
      opacity: controller.formOpacity.value.clamp(0.0, 1.0),
      child: Container(
        padding: const EdgeInsets.all(32.0),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.3),
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: Colors.white.withOpacity(0.2),
            width: 1,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.5),
              blurRadius: 20,
              spreadRadius: 2,
            ),
          ],
        ),
        child: Form(
          key: controller.formKey,
          child: Column(
            children: [
              // 用户名输入框
              _buildUsernameField(),
              const SizedBox(height: 20),
              // 密码输入框
              _buildPasswordField(),
              const SizedBox(height: 20),
              // 记住密码复选框
              _buildRememberPasswordRow(),
              const SizedBox(height: 30),
              // 登录按钮
              _buildLoginButton(),
              // 错误信息显示
              if (controller.hasError.value) ...[
                const SizedBox(height: 16),
                _buildErrorMessage(),
              ],
            ],
          ),
        ),
      ),
    );
  }

  /// 构建用户名输入框
  Widget _buildUsernameField() {
    return _buildInputField(
      controller: controller.usernameController,
      focusNode: controller.usernameFocusNode,
      hintText: '请输入用户名',
      prefixIcon: Icons.person_outline,
      onChanged: controller.onUsernameChanged,
      hasError: controller.validationErrors.containsKey('username'),
    );
  }

  /// 构建密码输入框
  Widget _buildPasswordField() {
    return _buildInputField(
      controller: controller.passwordController,
      focusNode: controller.passwordFocusNode,
      hintText: '请输入密码',
      prefixIcon: Icons.lock_outline,
      isPassword: true,
      isPasswordVisible: controller.isPasswordVisible.value,
      onPasswordVisibilityToggle: controller.togglePasswordVisibility,
      onChanged: controller.onPasswordChanged,
      hasError: controller.validationErrors.containsKey('password'),
    );
  }

  /// 构建通用输入框
  Widget _buildInputField({
    required TextEditingController controller,
    required FocusNode focusNode,
    required String hintText,
    required IconData prefixIcon,
    required Function(String) onChanged,
    bool isPassword = false,
    bool isPasswordVisible = false,
    VoidCallback? onPasswordVisibilityToggle,
    bool hasError = false,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: hasError 
              ? Colors.red.withOpacity(0.6)
              : Colors.white.withOpacity(0.3),
          width: 1.5,
        ),
        color: Colors.black.withOpacity(0.2),
      ),
      child: TextField(
        controller: controller,
        focusNode: focusNode,
        obscureText: isPassword && !isPasswordVisible,
        onChanged: onChanged,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            color: Colors.white.withOpacity(0.6),
            fontSize: 16,
          ),
          prefixIcon: Icon(
            prefixIcon,
            color: Colors.white.withOpacity(0.7),
          ),
          suffixIcon: isPassword
              ? IconButton(
                  icon: Icon(
                    isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  onPressed: onPasswordVisibilityToggle,
                )
              : null,
          border: InputBorder.none,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 16,
          ),
        ),
      ),
    );
  }

  /// 构建记住密码行
  Widget _buildRememberPasswordRow() {
    return Row(
      children: [
        GestureDetector(
          onTap: controller.toggleRememberPassword,
          child: Row(
            children: [
              Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.white.withOpacity(0.6),
                    width: 1.5,
                  ),
                  borderRadius: BorderRadius.circular(4),
                  color: controller.isRememberPassword.value
                      ? Colors.white.withOpacity(0.8)
                      : Colors.transparent,
                ),
                child: controller.isRememberPassword.value
                    ? const Icon(
                        Icons.check,
                        size: 14,
                        color: Colors.black87,
                      )
                    : null,
              ),
              const SizedBox(width: 8),
              Text(
                '记住密码',
                style: TextStyle(
                  color: Colors.white.withOpacity(0.8),
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: controller.isLoading.value ? null : controller.onLoginTap,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.white.withOpacity(0.9),
          foregroundColor: Colors.black87,
          elevation: 8,
          shadowColor: Colors.black.withOpacity(0.3),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: controller.isLoading.value
            ? const SizedBox(
                width: 24,
                height: 24,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.black54),
                ),
              )
            : const Text(
                '登录',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                  letterSpacing: 1.0,
                ),
              ),
      ),
    );
  }

  /// 构建错误信息
  Widget _buildErrorMessage() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Colors.red.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red.withOpacity(0.8),
            size: 16,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              controller.errorMessage.value,
              style: TextStyle(
                color: Colors.red.withOpacity(0.9),
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建忘记密码链接
  Widget _buildForgotPasswordLink() {
    return GestureDetector(
      onTap: controller.onForgotPasswordTap,
      child: Text(
        '忘记密码？',
        style: TextStyle(
          color: Colors.white.withOpacity(0.7),
          fontSize: 14,
          decoration: TextDecoration.underline,
          decorationColor: Colors.white.withOpacity(0.5),
        ),
      ),
    );
  }

  /// 构建底部信息
  Widget _buildBottomInfo() {
    return Column(
      children: [
        if (controller.lastLoginTime.value != null) ...[
          Text(
            '上次登录: ${_formatLastLoginTime(controller.lastLoginTime.value!)}',
            style: TextStyle(
              color: Colors.white.withOpacity(0.5),
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 8),
        ],
        Text(
          '© 2025 Flutter Standard Project',
          style: TextStyle(
            color: Colors.white.withOpacity(0.4),
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  /// 构建装饰元素
  Widget _buildDecorations() {
    return Positioned.fill(
      child: IgnorePointer(
        child: CustomPaint(
          painter: InkDropsPainter(),
        ),
      ),
    );
  }

  /// 格式化上次登录时间
  String _formatLastLoginTime(String timeString) {
    try {
      final dateTime = DateTime.parse(timeString);
      final now = DateTime.now();
      final difference = now.difference(dateTime);
      
      if (difference.inDays > 0) {
        return '${difference.inDays}天前';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return '未知';
    }
  }

  @override
  Widget build(BuildContext context) {
    // 设置登录页面专用的状态栏样式 - 深色背景使用浅色图标
    SystemUIUtils.setTransparentStatusBarLight();
    
    return GetBuilder<LoginController>(
      init: LoginController(),
      id: "login",
      builder: (_) {
        return Scaffold(
          backgroundColor: Colors.black,
          // 添加透明AppBar，不影响背景显示
          appBar: _buildTransparentAppBar(),
          // 让body延伸到AppBar下方，保持背景完整性
          extendBodyBehindAppBar: true,
          body: _buildView(),
        );
      },
    );
  }
  
  /// 构建透明AppBar
  PreferredSizeWidget _buildTransparentAppBar() {
    return AppBar(
      // 背景透明
      backgroundColor: Colors.transparent,
      // 去除阴影
      elevation: 0,
      // 使用浅色图标（适配深色背景）
      foregroundColor: Colors.white.withOpacity(0.8),
      // 不显示标题
      title: null,
      // 返回按钮改成X图标
      leading: IconButton(
        icon: Icon(
          Icons.close,
          color: Colors.white.withOpacity(0.8),
          size: 24,
        ),
        onPressed: () => Get.back(),
      ),
      // 可选的操作按钮
      actions: [
        IconButton(
          icon: Icon(
            Icons.help_outline,
            color: Colors.white.withOpacity(0.6),
            size: 22,
          ),
          onPressed: () {
            LoadingUtil.info('如需帮助，请联系管理员');
          },
        ),
      ],
      // 系统状态栏样式
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
        statusBarBrightness: Brightness.dark,
      ),
    );
  }
}

/// 水墨背景绘制器
class InkWashPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..style = PaintingStyle.fill
      ..strokeWidth = 1;

    // 绘制水墨渐变效果
    final gradient = RadialGradient(
      center: Alignment.topLeft,
      radius: 1.5,
      colors: [
        Colors.white.withOpacity(0.05),
        Colors.grey.withOpacity(0.02),
        Colors.transparent,
      ],
    );

    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    paint.shader = gradient.createShader(rect);
    canvas.drawRect(rect, paint);

    // 绘制一些水墨点效果
    paint.shader = null;
    paint.color = Colors.white.withOpacity(0.03);
    
    for (int i = 0; i < 20; i++) {
      final x = (size.width * (i * 0.13)) % size.width;
      final y = (size.height * (i * 0.17)) % size.height;
      final radius = (i % 3 + 1) * 15.0;
      
      canvas.drawCircle(Offset(x, y), radius, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

/// 水墨滴效果绘制器
class InkDropsPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.white.withOpacity(0.02)
      ..style = PaintingStyle.fill;

    // 绘制一些随机的墨滴效果
    final drops = [
      Offset(size.width * 0.1, size.height * 0.15),
      Offset(size.width * 0.9, size.height * 0.25),
      Offset(size.width * 0.15, size.height * 0.8),
      Offset(size.width * 0.85, size.height * 0.75),
    ];

    for (final drop in drops) {
      canvas.drawCircle(drop, 8, paint);
      canvas.drawCircle(drop.translate(5, 3), 4, paint);
      canvas.drawCircle(drop.translate(-3, 7), 6, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
